<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .slider-bar {
            position: absolute;
            left: 50%;
            top: 300px;
            margin-left: 600px;
            width: 45px;
            height: 130px;
            background-color: pink;
        }

        .w {
            width: 1200px;
            margin: 10px auto;
        }

        .header {
            height: 150px;
            background-color: purple;
        }

        .banner {
            height: 250px;
            background-color: skyblue;
        }

        .main {
            height: 1000px;
            background-color: yellowgreen;
        }

        span {
            /* 先是隐藏 */
            display: none;
            position: absolute;
            bottom: 0;
        }
    </style>
</head>
<body>
    <div class="slider-bar">
        <span class="goBack">返回顶部</span>
    </div>
    <div class="header w">头部区域</div>
    <div class="banner w">banner区域</div>
    <div class="main w">主体部分</div>
    <script>
        /* 
            window.pageYOffset   获取页面卷去的头部。
            页面滚动到一定的位置，侧边栏就会变成固定定位，固定在某个位置

        */
        var banner = document.querySelector('.banner');
        // 侧边栏
        var slider = document.querySelector('.slider-bar');
        // 侧边栏固定的位置
        var sliderTop = slider.offsetTop - banner.offsetTop;
        // banner 距顶部距离
        var bannerTop = banner.offsetTop;
        document.addEventListener('scroll', () => {
            // window.pageYOffset 卷去头部的距离
            if (window.pageYOffset > bannerTop) {
                slider.style.position = 'fixed';
                slider.style.top = sliderTop + 'px';
            } else {
                slider.style.position = 'absolute';
                slider.style.top = '300px';
            }
        });

    </script>
</body>
</html>